import { Component, OnInit, Input, Output, EventEmitter, ViewChild } from '@angular/core';

import { CudTableService } from '../../../../public/serve/cud-table/cud-table.service';
import { HintsService } from '../../../../public/serve/hints/hints.service';
import { RemoveTableService } from '../../../../public/serve/remove-table/remove-table.service';
import { PaginationComponent } from '../../../../public/pagination/pagination.component';
import { Service } from '../../../../server/server';
import { appProductUrl } from '../../../product.url';
import { product } from '../../../product.data';

declare var $: any;

@Component({
    selector: 'app-product-indexing-task-list-theme',
    templateUrl: './product-indexing-task-list-theme.component.html'
})
export class ProductIndexingTaskListThemeComponent implements OnInit {
    total: number = 0;
    naturalNum: number = 0;
    list: Array<object>;

    isSelectAll: boolean = false;
    isChose: boolean = false;
    queryCriteria: string = '';

    @Input() selectedThemeWordNames: string;                //选中的主题词名称(字符串)
    mThemeWordNames: Array<string> = [];                    //选中的主题词名称(数组)
    @Input() selectedThemeWordIds: string;                  //选中的主题词Id(字符串)
    mThemeWordIds: Array<string> = [];                      //选中的主题词Id(数组)
    @Input() taskName: string;                              //任务名称
    @Output() themeWordNames = new EventEmitter<string>();
    @Output() themeWordIds = new EventEmitter<string>();
    @ViewChild('pagination') pagination: PaginationComponent;

    taskData: any;
    type: string = '';

    constructor(
        private server: Service,
        private request: CudTableService,
        private hintsService: HintsService,
        public removeTableService: RemoveTableService) { }


    ngOnInit() {
    }

    getThemeWordTableList(type, data) {
        this._cancelChecked();
        //选中原先的
        if (this.selectedThemeWordIds) {
            this.mThemeWordIds = this.selectedThemeWordIds.split(',');
        }
        if (this.selectedThemeWordNames) {
            this.mThemeWordNames = this.selectedThemeWordNames.split(',');
        }

        this.type = type;
        this.taskData = data;
        if (type === 'mainTask' || (type === 'edit' && data.parentId === 0)) {
            this.getThemeTableList();
        } else {
            this.getTaskThemeTableList(data);
        }
    }

    getTaskThemeTableList(data) {
        let params = this.getTaskThemeTableListParams();
        if(this.type === 'edit') {
            params.taskId = data.parentId;
        }else if(this.type === 'addChildTask') {
            params.taskId = data.taskId;
        }
        this.request.postRequest(this.server.baseUrl +appProductUrl.getTaskThemeTableList, params).then((res: any) => {
            if (res.result_code === '0000') {
                this.list = res.result;
                this.total = res.length;
                this.naturalNum = product.pagination.naturalNum;
                if (this.mThemeWordIds && this.mThemeWordIds.length >= 0) {
                    for (let item of this.list) {
                        for (let child of this.mThemeWordIds) {
                            if (item['themeTableId'] == child) {
                                item['isChecked'] = true;
                                this.removeTableService.removeChose(true, item, this.list.length)['bool'];
                            }
                        }
                    }
                }
            } else {
                this.hintsService.messages(res.message, res.result_code);
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    getThemeTableList() {
        let params = this.getThemeTableListParams();
        this.request.postRequest(this.server.baseUrl +appProductUrl.getThemeTableList, params).then((res: any) => {
            if (res.result_code === '0000') {
                this.list = res.result;
                this.total = res.length;
                this.naturalNum = product.pagination.naturalNum;
                if (this.mThemeWordIds && this.mThemeWordIds.length >= 0) {
                    for (let item of this.list) {
                        for (let child of this.mThemeWordIds) {
                            if (item['themeTableId'] == child) {
                                item['isChecked'] = true;
                                this.removeTableService.removeChose(true, item, this.list.length)['bool'];
                            }
                        }
                    }
                }
            } else {
                this.hintsService.messages(res.message, res.result_code);
            }
            return;
        }).catch((err: any) => {
            this.hintsService.messages("error", "error");
            return;
        });
    }

    getThemeTableListParams() {
        return {
            token: product.retrieval.token,
            pageNo: product.pagination.pageNumber,
            pageSize: product.pagination.pageSize,
            startTime: null,
            endTime: null,
            checkStatus: null,
            status: null,
            themeTableCode: null,
            queryCriteria: this.queryCriteria
        }

    }

    getTaskThemeTableListParams() {
        return {
            token: product.retrieval.token,
            id: product.retrieval.id,
            themeTableId: '',
            pageNo: product.pagination.pageNumber,
            pageSize: product.pagination.pageSize,
            taskId: '',
            queryCriteria: this.queryCriteria
        }
    }

    /**
     * 全选
     * @param bool
     * @param keywordTabVal
     */
  _selectAll(bool, themeTableList) {
    this.isSelectAll = this.isChose = this.removeTableService.keywordRemoveAll(bool, themeTableList, 'themeTableId');
    if (!bool) {
        this.mThemeWordIds = [];
        this.mThemeWordNames = [];
        for (let item of themeTableList) {
            item['isChecked'] = bool;
        }
       
    } else {
        for (let item of themeTableList) {
            this.mThemeWordIds.push(item.themeTableId);
            if (item.name) {
                this.mThemeWordNames.push(item.name);
            } else if (item.themeWordTableName) {
                this.mThemeWordNames.push(item.themeWordTableName);
            }
        }
    }
  }

    /**
     * 单选
     * @param bool
     * @param name
     * @param length
     */
    _chose(bool, child, length) {
        if (!bool) {
            for (let item of this.list) {
                if (item['themeTableId'] === child.themeTableId) {
                    item['isChecked'] = !bool;
                }
            }
            
            var index = this.mThemeWordIds.indexOf(String(child.themeTableId));
            if (index > -1) {
                this.mThemeWordIds.splice(index, 1);
            }
            if (child.name) {
                var index1 = this.mThemeWordNames.indexOf(child.name);
                if (index1 > -1) {
                    this.mThemeWordNames.splice(index, 1);
                }
            } else if (child.themeWordTableName) {
                var index1 = this.mThemeWordNames.indexOf(child.themeWordTableName);
                if (index1 > -1) {
                    this.mThemeWordNames.splice(index, 1);
                }
            }
        } else {
            this.mThemeWordIds.push(child.themeTableId);
            if (child.name) {
                this.mThemeWordNames.push(child.name);
            } else if (child.themeWordTableName) {
                this.mThemeWordNames.push(child.themeWordTableName);
            }
        }

        this.removeTableService.removeChose(bool, child, length)['bool'];
    }

    /**
     * 重置表格复选框、选中的ID
     */
    public _cancelChecked() {
        this.isChose = false;
        this.list = [];
        // this.removeTableService.removeAll(false, '', '');
    }

    public dismissModal() {
        this.themeWordNames.emit(this.mThemeWordNames.toString());
        this.themeWordIds.emit(this.mThemeWordIds.toString());
        $("#distributeThemeTabs").modal('hide');
    }

    clearQueryCriteria() {
        this.mThemeWordNames = [];
        this.mThemeWordIds = [];
        // this.selectedThemeWordNames = '';
        // this.selectedThemeWordIds = '';
        this.queryCriteria = '';
        this.pagination.currentPage = 1;
        this.pagination.pageSize = 20;
        product.pagination.pageNumber = 1;
        product.pagination.pageSize = 20;
        product.pagination.naturalNum = 0;
        this.removeTableService.removeAll(false, '', '');
    }


    /**
     * 搜索
     * @param val
     */
    _retrieval(val: string) {
        this.queryCriteria = val.trim();

        // if (!this.type || (this.type === 'edit' && this.taskData.parentId === 0) || this.taskData.parentId === 0) {
        if (!this.type || (this.type === 'edit' && this.taskData.parentId === 0)) {
            this.getThemeTableList();
        } else {
            this.getTaskThemeTableList(this.taskData);
        }
    }
    /**
      * 分页
      * @param pagination 
      */
    _pagination(pagination: Array<any>) {
        product.pagination.pageNumber = pagination[0].pageNumber;
        product.pagination.pageSize = pagination[0].pageSize;
        product.pagination.naturalNum = (product.pagination.pageNumber - 1) * product.pagination.pageSize;

        // if (!this.type || (this.type === 'edit' && this.taskData.parentId === 0) || this.taskData.parentId === 0) {
        if (!this.type || (this.type === 'edit' && this.taskData.parentId === 0)) {
            this.getThemeTableList();
        } else {
            this.getTaskThemeTableList(this.taskData);
        }
    }
}

